// pages/trajectory/trajectory.js
const app = getApp();
const util = require('../../utils/util');
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //设置可停留时长
    showStop:false,
    //日期选择框
    showDate:false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    //显示的日期
    currentDateStr:util.timeFormatDay(new Date()),
    //明天日期
    tomorrow:util.timeFormatDay (new Date(new Date().getTime()+ 24*60*60*1000)),
    //轨迹
    polyline: [],
    //传参
    paramObj:{},
    //传参来的物联网数据
    iotData:{},
    //运行数据
    runArr:[],
    //地图中心点
    centerLog:'',
    centerLat:'',

    //统计到几天前
    dayNum:60,
    //地图上标记（用于所有轨迹数据在一个点上）
    markers:[],
    //用户权限
    authority: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { 
    this.setData({
      authority: app.globalData.authority
    })

    //设置统计几天数据
    this.getBeforeDate();

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);

      console.log('轨迹传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      let iotData=paramObj.iotData;     
      if(iotData.lng && iotData.lat){        
        this.setData({
          iotData: iotData,
          centerLog:iotData.lng,
          centerLat:iotData.lat,
        }) 
      }else{
        this.setData({          
          centerLog:'116.411168',
          centerLat:'39.898331'
        })
      } 

      //获取轨迹数据
      this.getTrajectoryData();

    }else{
      Toast.fail('暂无轨迹数据');
      this.setData({          
        centerLog:'116.411168',
        centerLat:'39.898331'
      })
    }  
  },

  //获取轨迹数据
  getTrajectoryData(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    //清空数据
    this.setData({ 
      runArr: [],
      polyline: []
    })
    
    let param={
      imei: this.data.paramObj.imei,
      startTime: this.data.currentDateStr
    }

    CommonService.trajectory(param).then(res=>{
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;

        //计算运行时间 
        let runArr=[];
        for(let i=0;i<result.length;i++){
          let start=new Date((result[i].locusStartTime).replaceAll("-","/"));
          let end=new Date((result[i].endTime).replaceAll("-","/"));
          let long=(end-start)/1000;

          if(long>0){
            long=util.secondToFormat(long);

            result[i].start=(result[i].locusStartTime).slice(11);
            result[i].end=(result[i].endTime).slice(11);
            result[i].long=long;

            runArr.push(result[i]);
          }               
        }

        if(runArr.length){
          console.log('轨迹数据');
          console.log(runArr);

          this.setData({ 
            runArr: runArr
          })

          //显示当天所有数据的轨迹
          this.showAllTrajectory();

        }else{
          Toast.fail('暂无轨迹数据');
          //把定位点显示到地图上
          this.showMarker();
        }
      }else{
        Toast.fail('暂无轨迹数据');
        //把定位点显示到地图上
        this.showMarker();
      }

    }).catch((error) => {
      Toast.clear();         
    })
  },  

  //判断轨迹数组中的值是否在一个点上
  isOnePoint(arr){
    let lng=arr[0].longitude;
    let lat=arr[0].latitude; 
    
    let lngFlag=arr.every(item=>{
      return item.longitude==lng
    });

    let latFlag=arr.every(item=>{
      return item.latitude==lat
    });
    
    if(lngFlag && latFlag){
      return true;
    }else{
      return false;
    }
  },

  //显示当天所有数据的轨迹
  showAllTrajectory(){
    let runArr=this.data.runArr;    
    let pointsArr=[];

    //获取坐标
    for(let i=0;i<runArr.length;i++){
      let locationArr=runArr[i].location;
      locationArr.forEach(item => {
        let obj={
          longitude:item.lng,
          latitude:item.lat,
        }
        pointsArr.push(obj);
      });      
    }

    if(this.isOnePoint(pointsArr)){
      let markers=[];
      let marker={
        id:0,
        latitude: pointsArr[0].latitude,
        longitude: pointsArr[0].longitude, 
        width:10,
        height:10
      }
      markers.push(marker);
      this.setData({ 
        markers: markers 
      })
    }else{
      this.setData({ 
        markers: []
      })
    }

    this.setData({
      //画折线 
      polyline: [{
        points: pointsArr,
        color:"#FF0000DD",
        width: 4,
        arrowLine:true
      }],      
      centerLog:pointsArr[0].longitude,
      centerLat:pointsArr[0].latitude  
    })
  },
  
  //点击时段显示轨迹
  onShowTrajectory(e){
    let runArr=this.data.runArr;
    let detail=e.currentTarget.dataset.detail;     
    let locationArr=detail.location;
    let pointsArr=[];

    //获取坐标
    for(let i=0;i<locationArr.length;i++){
      let obj={
        longitude:locationArr[i].lng,
        latitude:locationArr[i].lat,
      }
      pointsArr.push(obj);
    }

    if(pointsArr.length<=1){
      Toast({
        type: 'fail',
        message: '暂无轨迹数据',
        duration: 1000,
      });
    }

    //当前样式
    for(let i=0;i<runArr.length;i++){
      runArr[i].current=false;
      if(runArr[i].id==detail.id){
        runArr[i].current=true;
      }
    }
   
    if(this.isOnePoint(pointsArr)){
      let markers=[];
      let marker={
        id:0,
        latitude: pointsArr[0].latitude,
        longitude: pointsArr[0].longitude,
        width:10,
        height:10 
      }
      markers.push(marker);
      this.setData({ 
        markers: markers 
      })
    }else{
      this.setData({ 
        markers: []
      })
    }
      
    this.setData({
      //画折线 
      polyline: [{
        points: pointsArr,
        color:"#FF0000DD",
        width: 4,
        arrowLine:true
      }],
      runArr:runArr,
      centerLog:pointsArr[0].longitude,
      centerLat:pointsArr[0].latitude    
    })
  },  

  //设置可选的最小日期
  getBeforeDate(){
    let rusult=util.countPrevDay(new Date(),this.data.dayNum);
    this.setData({ 
			minDate: rusult
		})
  },

  //显示日期选择框
  onShowDate(){
    this.setData({ 
			showDate: true
		})
  },

  //关闭日期选择框
  onCloseDate(){
    this.setData({ 
			showDate: false
		}) 
  },

  //确定日期时
  onConfirmDate(event){
    let currentDate=event.detail;
    this.setData({
      currentDate: currentDate,
      currentDateStr: util.timeFormatDay(currentDate),      
      tomorrow: util.timeFormatDay(new Date(currentDate+ 24*60*60*1000)), 			
    })

    //关闭日期选择框
    this.onCloseDate();

    //请求轨迹数据
    this.getTrajectoryData();
  },

  //点击查看所有轨迹
  onLookAll(){
    this.showAllTrajectory();

    //清除当前样式
    let runArr=this.data.runArr;
    for(let i=0;i<runArr.length;i++){
      runArr[i].current=false;
    }
    this.setData({ 
			runArr: runArr 
		})
  },

  //如果无轨迹数据，把定位点显示到地图上
  showMarker(){
    let markers=[];
    let marker={
      id:0,
      latitude: this.data.centerLat,
      longitude: this.data.centerLog      
    }
    markers.push(marker);
    this.setData({ 
      markers: markers 
    })
  },  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})